package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.util.JwtTokenUtil;
import com.example.util.UnionidUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;


@RestController
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);


    @PostMapping("/login")
//    @JwtIgnore
    public JSONObject adminLogin(HttpServletResponse response, String username, String password) {

        // 模拟默认登录成功，返回用户ID和角色信息
        String userId = UUID.randomUUID().toString();
        String role = "admin";

        // 创建token
        String token = JwtTokenUtil.createToken(userId, username, role);
        log.info("### 登录成功, token={} ###", token);

        // 将token放在响应头
        response.setHeader(JwtTokenUtil.TOKEN_HEADER, JwtTokenUtil.TOKEN_PREFIX + token);
        // 将token响应给客户端
        JSONObject result = new JSONObject();
        result.put("token", token);
        return result;
    }


    @RequestMapping("third")
    public JSONObject getThirdToken(String code) {
        String unionid = UnionidUtils.getUnionid(code);
        String token = JwtTokenUtil.createToken(unionid);
        JSONObject result = new JSONObject();
        result.put("token", token);
        return result;
    }

    @RequestMapping("/inside")
    public JSONObject getInsideToken() {
        String token = JwtTokenUtil.createToken();
        JSONObject result = new JSONObject();
        result.put("token", token);
        return result;

    }

    @RequestMapping("thirdwx")
    public JSONObject getThirdToken(String appid, String openid) {
        String token = JwtTokenUtil.createToken(appid, openid);
        JSONObject result = new JSONObject();
        result.put("token", token);
        return result;

    }

    /**
     * 解析jwt
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/users")
    public JSONObject userList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取请求头信息authorization信息
        final String authHeader = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
        log.info("## authHeader= {}", authHeader);
        try {
            JSONObject calmis = JwtTokenUtil.checkJWT(authHeader);
            return calmis;
        } catch (Exception e) {
            return JSONObject.parseObject(e.getMessage());
        }
    }


}
